Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
How to mock all methods of the "chalk" library?

I'm using chalk to style terminal text and I wrote some helper functions to return chalk instances:

/* colorUtils.js */
const chalk = require("chalk");

function redUnderline(text) {
  return chalk.red.underline(text);
}
function greenUnderline(text) {
  return chalk.green.underline(text);
}

module.exports = { redUnderline, greenUnderline };

To test the above functions, I used Jest to write my test suite:

/* colorUtils.test.js */
const chalk = require("chalk");
const { redUnderline, greenUnderline } = require("./colorUtils");

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}));

describe("colorUtils", () => {
  describe("redUnderline", () => {
    it("should return a red, underlined string", () => {
      const result = redUnderline("foo");
      expect(chalk.red.underline).toHaveBeenCalledWith("foo");
    });
  });
  describe("greenUnderline", () => {
    it("should return a green, underlined string", () => {
      const result = greenUnderline("foo");
      expect(chalk.green.underline).toHaveBeenCalledWith("foo");
    });
  });
});

The above test suite passes without problems.

However, in order to test that chalk.red.underline and chalk.green.underline is called properly, I need to mock chalk using jest.mock() with the following code:

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}))

Is there a more compact syntax of jest.mock() such that it mocks all chalk instance methods to become jest.fn()?

I tried using the following mock method:

jest.mock("chalk");

However, the first test will fail:

    TypeError: Cannot read property 'underline' of undefined

      2 |
      3 | function redUnderline(text) {
    > 4 |   return chalk.red.underline(text);
        |                    ^
      5 | }
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!